import org.apache.zookeeper.*;

import java.util.Arrays;
import java.util.List;

public class Main {
    public static final String ROOT = "/admin"; //根节点

    public static void main(String[] args) throws Exception {

        // 创建连接
        ZooKeeper zooKeeper = new ZooKeeper("192.168.75.50:2181", 3000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("状态State:" + event.getState());
                System.out.println("类型Type:" + event.getType());
                System.out.println("Wrapper:" +event.getWrapper());
                System.out.println("路径Path:" + event.getPath());
            }
        });



        // 创建节点

        zooKeeper.create("/admin","root".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

        //2.2 子节点,持久化顺序编号目录节点
         zooKeeper.create("/admin/node1","/root/node1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
         zooKeeper.create("/admin/node2","/root/node2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

        //2.3 子节点 临时目录节点 客户端与zookeeper断开连接后，该节点被删除
        //zooKeeper.create("/root/node3", "/root/node3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        //2.4 子节点 session 过期自动删除，也会加数字的后缀
        //zooKeeper.create("/root/node4", "/root/node4".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        //3.查看节点

        List<String> ktvs = zooKeeper.getChildren(ROOT, true);
        System.out.println("所有子节点:" + Arrays.toString(ktvs.toArray()));

        //4.删除子节点
        for (String nodeId : ktvs){
            zooKeeper.delete(ROOT + "/" + nodeId,-1);
        }

        //删除根节点
        zooKeeper.delete(ROOT,0);
        zooKeeper.close();
    }
}
